package cn.virens.web.components.websocket;

import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.virens.database.mysql.model.sys.SysUser;
import cn.virens.web.components.shiro.comm.SessionUtil;

public class WebSocketHandshakeInterceptor implements HandshakeInterceptor {
	protected final Logger logger = LoggerFactory.getLogger(WebSocketHandshakeInterceptor.class);

	@Override
	public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {
		return WebSocketUtil.bool(WebSocketUtil.useSession(request, (session) -> {
			SysUser sessionUserInfo = SessionUtil.getUserInfo(session);
			String sessionGroups = SessionUtil.getGroupKeys(session);
			String sessionRoles = SessionUtil.getRoleKeys(session);

			if (ObjectUtil.isAllNotEmpty(sessionUserInfo, sessionRoles, sessionGroups)) {
				attributes.put(SessionUtil.LOGIN_USER_INFO, sessionUserInfo);
				attributes.put(SessionUtil.LOGIN_GROUP_KEY, sessionGroups);
				attributes.put(SessionUtil.LOGIN_ROLE_KEY, sessionRoles);
			} else {
				return false;
			}

			return true;
		}));
	}

	@Override
	public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, WebSocketHandler wsHandler, Exception exception) {
		logger.debug("WebSocketHandshakeInterceptor.afterHandshake");
	}

}
